package org.dizem.groupon.action;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import org.dizem.groupon.model.domain.UserEntity;
import org.dizem.groupon.service.UserService;

import java.util.Map;

import static org.dizem.groupon.Constants.*;

/**
 * User: dizem@126.com
 * Time: 11-6-23 下午8:39
 */
public class LoginAction extends ActionSupport {
	private UserService service;
	private String username;
	private String password;
	private String validation;

	public UserService getService() {
		return service;
	}

	public void setService(UserService service) {
		this.service = service;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getValidation() {
		return validation;
	}

	public void setValidation(String validation) {
		this.validation = validation;
	}

	@Override
	public void validate() {

		try {
			String code = (String) ActionContext.getContext().getSession().get(VALIDATION_CODE);
			if (!validation.equalsIgnoreCase(code)) {
				addFieldError("validation", "验证码错误");
				return;
			}

			if (getFieldErrors().size() != 0)
				return;

			if (!service.usernameOrEmailExists(username)) {
				addFieldError("username", "用户名或邮箱不存在");
				return;
			}
			if (!service.validateByEmail(username, password)
					&& !service.validateByUsername(username, password)) {
				addFieldError("password", "密码错误");
			}

		} finally {
			ActionContext.getContext().getSession().remove(VALIDATION_CODE);
		}
	}

	@Override
	public String execute() throws Exception {
		UserEntity user = service.getByUsername(username);
		Map<String, Object> session = ActionContext.getContext().getSession();
		session.put(SESSION_USERNAME, username);
		session.put(SESSION_USER_TYPE, USER_TYPE_NAME[user.getAccountType()]);
		if (user.getAccountType() == 1) {
			return "admin_login";
		} else {
			return "user_login";
		}
	}
}
